<template>
    <div class="job">
        <el-button type="primary" @click="addJob('添加职位')">添加职位</el-button>
        <el-button type="danger" @click="delJobSelection()">批量删除</el-button>
        <el-table
            ref="multipleTableRef"
            :data="tableData"
            style="width: 100%;height: 420px;"
            @selection-change="handleSelectionChange"
        >
            <el-table-column type="selection" width="55" />
            <el-table-column property="id" label="id" width="55" />
            <!-- <el-table-column property="name" label="企业名称" width="120" /> -->
            <!-- <el-table-column property="industry" label="所属行业" width="120" /> -->
            <el-table-column property="job" label="职位" width="120" />
            <el-table-column property="salary" label="薪资" width="120" />
            <el-table-column property="education" label="学历" width="60" />
            <el-table-column property="experience" label="经验" width="60" />
            <el-table-column property="number" label="招聘人数" width="80" />
            <el-table-column label="发布时间" width="160">
            <template #default="scope">{{ scope.row.releaseTime }}</template>
            </el-table-column>
            <el-table-column label="截止时间" width="160">
            <template #default="scope">{{ scope.row.validTime }}</template>
            </el-table-column>
            <el-table-column property="views" label="浏览量" width="80" />
            <el-table-column property="address" label="工作地点" show-overflow-tooltip />
            <el-table-column property="valid" label="是否上线" width="80" >
              <template #default="scope">
                <el-switch v-model="scope.row.valid" @click="setValid(scope.row)"
                  :active-value="1"
                  :inactive-value="0"
                />
              </template>
            </el-table-column>
            <el-table-column label="操作">
                <template #default="scope">
                    <el-button size="small" @click="handleEdit(scope.row.id, scope.row)"
                    >编辑</el-button
                    >
                    <el-button
                    size="small"
                    type="danger"
                    @click="handleDelete(scope.row.id, scope.row)"
                    >删除</el-button
                    >
                </template>
            </el-table-column>
        </el-table>
        <el-pagination class="page" background layout="prev, pager, next, jumper, sizes" :page-sizes="[10, 20, 30, 40]" hide-on-single-page v-model:page-size="param.pageSize" :total="page.total" @size-change="handleSizeChange " @current-change="getJobPage"  />
    
        <!-- 弹出框 -->
        <el-dialog v-model="dialogFormVisible" :title="dialogTitle">
          <mForm @submitForm="submitForm" :user-data="userData"/>
        </el-dialog>

        <!-- 弹出框 -->
        <el-dialog v-model="eitdDialogFormVisible" title="编辑职位">
          <el-form
            ref="ruleFormRef"
            :model="ruleForm"
            status-icon
            :rules="rules"
            label-position="left"
            label-width="100px"
            class="demo-ruleForm"
          >
            <el-form-item label="职位名称" prop="job">
              <el-input v-model="ruleForm.job" type="input" autocomplete="off" />
            </el-form-item>
            <el-form-item label="薪资" prop="salary">
              <el-input v-model="ruleForm.salary" type="input" autocomplete="off" />
            </el-form-item>
            <el-form-item label="学历" prop="education">
              <el-input v-model="ruleForm.education" type="input" autocomplete="off" />
            </el-form-item>
            <el-form-item label="经验" prop="experience">
              <el-input v-model="ruleForm.experience" type="input" autocomplete="off" />
            </el-form-item>
            <el-form-item label="工作地点" prop="address">
              <el-input v-model="ruleForm.address" type="input" autocomplete="off" />
            </el-form-item>
            <el-form-item label="招聘人数" prop="number">
              <el-input v-model.number="ruleForm.number" />
            </el-form-item>
            <el-form-item label="截止时间" prop="validTime">
              <el-date-picker
                    v-model="ruleForm.validTime"
                    type="date"
                    label="选择时间"
                    placeholder="选择时间"
                    style="width: 100%"
                  />
            </el-form-item>
            <el-form-item label="职位描述" prop="description">
              <el-input v-model="ruleForm.description" type="textarea" autocomplete="off" />
            </el-form-item>
            
            <el-form-item>
              <el-button type="primary" @click="submitForm1(ruleFormRef)"
                >提交</el-button
              >
              <el-button @click="resetForm(ruleFormRef)">重置</el-button>
            </el-form-item>
          </el-form>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup>
    import { getUser } from '../../api/otherApi.js'
    import { getJob,delJob ,editJob,getJobById} from '../../api/enterprise.js'
    import { onMounted, reactive, ref } from 'vue'
    import { ElTable,ElMessage,FormInstance, FormRules } from 'element-plus'
    import { showConfirmDialog } from 'vant'
    import mForm from '../../components/form/form.vue'
    import editForm from '../../components/enterprise/editForm.vue'

    const dialogFormVisible = ref(false)
    const eitdDialogFormVisible = ref(false)
    const dialogTitle = ref('弹出框标题')

    const userData = ref({})

    const jobId = ref<Number>(0)
    
    interface Job {
        address: String,
        avatar: String,
        company_profile: String,
        description: String,
        education: String
        eid: Number,
        experience: String
        id: Number,
        industry: String,
        job: String,
        name: String,
        number: String,
        releaseTime: String,
        salary: String,
        username:String,
        valid: Number,
        validTime: String,
        views:Number
    }
    interface Param {
        pageNum:Number,	//pageNum
        pageSize: Number,//每页个数
        keyword:String
    }

    const param = reactive<Param>({
		pageNum:1,	//pageNum
		pageSize: 10,//每页个数
		keyword:''
	})
    const page = ref<any>({})

    const multipleTableRef = ref<InstanceType<typeof ElTable>>()
    const multipleSelection = ref<Job[]>([])
    const delJobSelection = () => {
        let idList:Number[] = []
        multipleSelection.value.forEach(e=>{
            idList.push(e.id)
        })
        del(idList,"确定要删除已勾选的岗位吗？")
    }
    const handleSelectionChange = (val: Job[]) => {
        multipleSelection.value = val
    }
    const tableData = ref<Job[]>([])
    onMounted(async ()=>{
        getJob1()
        let user = await getUser('enterprise');
        userData.value = user.data
    })
    const getJob1 = async ()=>{
        const data = await getJob(param)
        tableData.value = data.data.records
        page.value = data.data
        console.log(tableData.value)
    }
    const del = (idList: Number[],msg: String = "确定要删除吗？")=>{
        if(idList.length){
            showConfirmDialog({
                title: '删除',
                message: msg,
            })
            .then(() => {
                delJob({idList:idList.join()}).then(res=>{
                    if(res.code === 200){
                        getJob1()
                    }
                })
            })
            .catch(() => {
                return;
            }); 
            
        }else{
            ElMessage({
                showClose:true,
                message:"请勾选需要删除的岗位！",
                type:'error'
            })
        }
    }

    
    const handleDelete = (id: number, row: Job) => {
        let idList:Number[] = [id]
        del(idList)
    }
    const getJobPage = (p:number)=>{
      param.pageNum = p
      getJob1()
    }
    const handleSizeChange = (val: number) => {
      param.pageSize = val
      getJob1()
    }

    const submitForm = (val)=>{
      dialogFormVisible.value = val
      console.log(dialogFormVisible.value)
      getJob1()
    }

    const addJob = (title)=>{
      dialogFormVisible.value = true
      dialogTitle.value = title
    }

    // 编辑职位表单
    const ruleFormRef = ref<FormInstance>()

    const ruleForm = reactive({
      address: '',
      avatar: '',//企业logo
      company_profile: '',//公司简介
      description: '',//职位描述
      education: '', //学历
      eid: 0,
      experience: '',//经验
      id: 0,
      industry: '',//行业
      job: '',//职位名称
      name: '',//企业名称
      number: 1,//招聘人数
      releaseTime: '',//发布时间
      salary: '',//薪资
      username:'',//企业用户名
      valid: 1, //是否上线
      validTime: '',  //有效时间
      views:0,
    })
    const handleEdit = async (id: number, row: Job) => {
      let data = await getJobById({id})
      let formData = data.data
      console.log(formData)
      if(formData){
        ruleForm.address= formData.address
        ruleForm.avatar= formData.avatar//企业logo
        ruleForm.company_profile= formData.company_profile//公司简介
        ruleForm.description=formData.description//职位描述
        ruleForm.education= formData.education //学历
        ruleForm.eid= formData.eid
        ruleForm.experience= formData.experience//经验
        ruleForm.id= formData.id
        ruleForm.industry= formData.industry//行业
        ruleForm.job= formData.job//职位名称
        ruleForm.name= formData.name//企业名称
        ruleForm.number= parseInt(formData.number)//招聘人数
        ruleForm.releaseTime= formData.releaseTime//发布时间
        ruleForm.salary= formData.salary//薪资
        ruleForm.username=formData.username//企业用户名
        ruleForm.valid= formData.valid //是否上线
        ruleForm.validTime= formData.validTime //有效时间
        ruleForm.views = formData.views
      }
      eitdDialogFormVisible.value = true
    }

    //是否上线开关
    const setValid = async (row)=>{
      let res = await editJob(row)
    }

    const rules = reactive<FormRules>({
      job: [{ required: true, message: '职位名称不能为空！', trigger: 'blur' }],
      salary: [{ required: true, message: '薪资不能为空！', trigger: 'blur' }],
      education: [{ required: true, message: '学历不能为空！', trigger: 'blur' }],
      experience: [{ required: true, message: '经验不能为空！', trigger: 'blur' }],
      description: [{ required: true, message: '职位描述不能为空！', trigger: 'blur' }],
      address: [{ required: true, message: '工作地点不能为空！', trigger: 'blur' }],
      number: [{ required: true, message: '招聘人数不能为0！', trigger: 'blur' },
      { type: 'number',min: 1, max: 10, message: '招聘人数1~10人', trigger: 'blur' }],
      validTime: [{ required: true, message: '截止时间不能为空！', trigger: 'blur' }],
    })
    const resetForm = (formEl: FormInstance | undefined) => {
      console.log(formEl)
      if (!formEl) return
      formEl.resetFields()
    }
    const submitForm1 = (formEl: FormInstance | undefined) => {
      if (!formEl) return
      formEl.validate(async (valid) => {
        if (valid) {
          await editJob(ruleForm).then(res=>{
            if(res.code === 200){
              eitdDialogFormVisible.value = false;
              resetForm(ruleFormRef.value)
              getJob1()
            }
          })
        } else {
          console.log('error submit!')
          return false
        }
      })
      
    }
</script>

<style lang="scss" scoped>
    .job{
        .page{
            position: absolute;
            bottom: 20px;
        }
    }
</style>
